const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const User = require('./User');

// 定义部门模型
const Department = sequelize.define('Department', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    validate: {
      notEmpty: true
    }
  },
  description: {
    type: DataTypes.TEXT
  },
  managerId: {
    type: DataTypes.INTEGER,
    allowNull: true,
    references: {
      model: User,
      key: 'id'
    },
    onUpdate: 'SET NULL',
    onDelete: 'SET NULL'
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive'),
    defaultValue: 'active'
  }
}, {
  timestamps: true,
  underscored: true,
  tableName: 'departments'
});

// 关联用户（部门经理）
Department.belongsTo(User, { as: 'Manager', foreignKey: 'managerId' });
User.hasOne(Department, { as: 'ManagedDepartment', foreignKey: 'managerId' });

// 部门与用户的多对多关系（一个部门有多个用户）
Department.belongsToMany(User, {
  through: 'user_departments',
  foreignKey: 'departmentId',
  as: 'Users'
});
User.belongsToMany(Department, {
  through: 'user_departments',
  foreignKey: 'userId',
  as: 'Departments'
});

module.exports = Department;